/**
 * @description 高德地图
 * @returns {Element}
 */
import AMapLoader from "@amap/amap-jsapi-loader";
import { getIcon } from "@/utils/index.js";
export default class MyMap {
  eleId; //容器的id
  myMap; //地图
  startIcon = null; //开始icon
  endIcon = null; //结束icon

  constructor(eleId) {
    this.eleId = eleId;
    this.initMap();
  }

  // 初始化地图
  initMap() {
    window._AMapSecurityConfig = {
      securityJsCode: "61258ac26f3c33107ed508b2bc106e31", //安全密钥
    };
    AMapLoader.load({
      key: "f18fa7a585b1ff81b1e92c4c7ca959b2", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: [
        "AMap.AutoComplete",
        "AMap.PlaceSearch",
        "AMap.Driving",
        "AMap.DragRoute",
      ],
    })
      .then((AMap) => {
        this.myMap = new AMap.Map(this.eleId, {
          //设置地图容器id
          viewMode: "3D", //是否为3D地图模式
          zoom: 13, //初始化地图级别
          center: [113.808299, 34.7917872], //初始化地图中心点位置
          resizeEnable: true,
          mapStyle: "amap://styles/darkblue", //设置地图的显示样式
        });

        //设置开始的icon
        let startImage = getIcon("images/startIcon.png");
        let startSize = [72, 94];
        this.startIcon = this.setIcon(startImage, startSize);
        //设置结尾的icon
        let endImage = getIcon("images/endIcon.png");
        let endSize = [43.32, 49.22];
        this.endIcon = this.setIcon(endImage, endSize);
      })
      .catch((e) => {
        console.log(e);
      });
  }

  //天气查询插件
  getWeather(address, callback) {
    AMap.plugin("AMap.Weather", function () {
      // 创建天气查询实例
      let weather = new AMap.Weather();
      // 执行实时天气信息查询
      weather.getForecast(address, function (err, data) {
        return callback(err, data)
      });
    });
  }

  //   设置icon
  setIcon(image, size) {
    return {
      type: "image", // 图标类型，现阶段只支持 image 类型
      image, // 图片 url
      size, // 图片尺寸
      anchor: "center", // 图片相对 position 的锚点，默认为 bottom-center
    };
  }

  // 设置标注
  setLabel(name, position, icon, textContent, textOffset) {
    return {
      name,
      position,
      zooms: [10, 20],
      opacity: 1,
      zIndex: 10,
      fold: true,
      icon,
      text: {
        // 要展示的文字内容
        content: textContent,
        // 文字方向，有 icon 时为围绕文字的方向，没有 icon 时，则为相对 position 的位置
        direction: "right",
        // 在 direction 基础上的偏移量
        offset: textOffset,
        // 文字样式
        style: {
          // 字体大小
          fontSize: 12,
          // 字体颜色
          fillColor: "#22886f",
          strokeColor: "#fff",
          strokeWidth: 2,
          fold: true,
          padding: "2, 5",
        },
      },
    };
  }

  //设置开始点标注
  setStartLabel(position, textContent) {
    let textOffset = [20, 5];
    return this.setLabel(
      "起点",
      position,
      this.startIcon,
      textContent,
      textOffset
    );
  }
  // 设置结束点标注
  setEndLabel(position, textContent) {
    let textOffset = [20, 5];
    return this.setLabel(
      "终点",
      position,
      this.endIcon,
      textContent,
      textOffset
    );
  }
  // 添加标注
  addLabel(path) {
    const labelsData = [
      this.setStartLabel(path[0], "起点"),
      this.setEndLabel(path[path.length - 1], "终点"),
    ];
    const markers = [];
    // 初始化 labelMarker
    labelsData.forEach((item, index) => {
      item.extData = {
        index,
      };
      const labelMarker = new AMap.LabelMarker(item);
      markers.push(labelMarker);
    });
    const layer = new AMap.LabelsLayer({
      zooms: [3, 20],
      zIndex: 1000,
      allowCollision: false, // 设置 allowCollision：true，可以让标注避让用户的标注
    });
    // 将 marker 添加到图层
    layer.add(markers);
    // 图层添加到地图
    this.myMap.add(layer);
  }
  // 绘制车辆行驶线路
  drawPolyline(path) {
    // 生成随机颜色
    let lineColor = "#" + Math.random().toString(16).slice(2, 5);
    const routeLine = new AMap.Polyline({
      path,
      isOutline: true,
      outlineColor: lineColor,
      borderWeight: 2,
      strokeWeight: 6,
      strokeOpacity: 0.5,
      strokeColor: lineColor,
      lineJoin: "round",
    });
    this.myMap.add(routeLine);
  }
  // 添加折线标记
  addLine(position) {
    let that = this; //修改this指向
    let startPosition = new AMap.LngLat(position.startLng, position.startLat);
    let endPosition = new AMap.LngLat(position.endLng, position.endLat);
    let driving = new AMap.Driving({
      map: that.map,
      policy: AMap.DrivingPolicy.LEAST_TIME,
      ferry: 1, // 是否可以使用轮渡
      hideMarkers: true, // 设置隐藏路径规划的起始点图标
      showTraffic: false, //实时路况
    });
    // 根据起终点经纬度规划驾车导航路线
    driving.search(startPosition, endPosition, function (status, result) {
      if (status === "complete") {
        console.log("绘制驾车路线完成");
        if (result.routes && result.routes.length) {
          that.drawRoute(result.routes[0]);
        }
      } else {
        console.log("获取驾车数据失败：" + result);
      }
    });
  }
  // 绘制路线
  drawRoute(route) {
    const path = this.parseRouteToPath(route);
    // 添加标注
    this.addLabel(path);
    // 绘制车辆行驶线路
    this.drawPolyline(path);
  }

  parseRouteToPath(route) {
    var path = [];
    route.steps?.forEach((stepsItem) => {
      stepsItem.path?.forEach((item) => {
        path.push(item);
      });
    });
    return path;
  }
}
